package cn.com.ghy.android.widget.chat;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.ghy.android.bean.OrderDetailBean;
import cn.com.ghy.android.bean.UnitInfoBean;
import cn.com.ghy.android.service.OrderOpeService;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.util.CommonUtil;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:添加订单信息弹出页面
 * @author wuz  @date 2011-5-17 10:14:35
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012 
 */

public class OrderInfoModifyPop extends Activity {

	private EditText txtSKU = null;
	private EditText txtShopCode = null;
	private EditText txtOrderNum = null;
	private EditText txtOrderPrice = null;
	private EditText txtOrderComments = null;
	private TextView labTxtMatnr = null;
	private TextView labTxtMaktx = null;

	private Spinner spiUnitInfo = null;

	private Button btnSubmit = null;
	private Button btnCancel = null;

	private List<UnitInfoBean> listUnitInfo = null;
	private OrderDetailBean orderDetail = null;
	private Intent intent = null;
	private Bundle bundle = null;
	private int position = -1;

	private ProgressDialog progressDialog = null;

	private HttpThread thread = null;
	boolean flag = false;

	@SuppressWarnings("unused")
	private static final String TAG = "OrderInfoModifyPop";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.order_info_modify);
		getSession();
		findView();
		initView();
		addListener();
		if (null != orderDetail && position != -1) {
			setView();
		} else {
			orderDetail = new OrderDetailBean();
		}
	}

	private void addListener() {
		spiUnitInfo.setOnItemSelectedListener(spiListener);
		btnSubmit.setOnClickListener(btnListener);
		btnCancel.setOnClickListener(btnListener);
		txtSKU.setKeyListener(CommonUtil.charNumListener);
		txtSKU.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				String str = ((EditText) v).getText().toString();
				if (!hasFocus && !"".equals(str)) {
					txtSKU.setText(str.toUpperCase());
				}
			}
		});
		txtShopCode.setKeyListener(CommonUtil.charNumListener);

		txtOrderPrice.addTextChangedListener(txtOrderPriceListener);
		txtOrderPrice.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				String str = ((EditText) v).getText().toString();
				if (!hasFocus && !"".equals(str)) {
					if (Double.parseDouble(str) > 500 || Double.parseDouble(str) < 0) {
						Toast.makeText(OrderInfoModifyPop.this, "单价不能超过500元", 5).show();
						txtOrderPrice.setText("");
					}
				}
			}
		});
	}

	private TextWatcher txtOrderPriceListener = new TextWatcher() {

		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

		public void afterTextChanged(Editable s) {
			String temp = s.toString();
			int posDot = temp.indexOf(".");
			if (posDot <= 0)
				return;
			if (temp.length() - posDot - 1 > 2) {
				s.delete(posDot + 3, posDot + 4);
			}
		}
	};

	private OnItemSelectedListener spiListener = new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			orderDetail.setUnitInfo((UnitInfoBean) parent.getItemAtPosition(position));
		}

		public void onNothingSelected(AdapterView<?> parent) {

		}
	};

	private View.OnClickListener btnListener = new View.OnClickListener() {

		public void onClick(View v) {
			Button button = (Button) v;
			switch (button.getId()) {
				case R.id.btnSubmit :
					if ("".equals(txtSKU.getText().toString())) {
						Toast.makeText(OrderInfoModifyPop.this, "请输入SKU!", Toast.LENGTH_SHORT)
								.show();
						break;
					} else if (!txtOrderNum.getText().toString().matches("^[0-9]*[1-9][0-9]*$")) {
						Toast.makeText(OrderInfoModifyPop.this, "请输入订单数量!", Toast.LENGTH_SHORT)
								.show();
						break;
					} else if (!txtOrderPrice.getText().toString()
							.matches("(([1-9][0-9]{0,3}((\\.[0-9]{1,2}){0,1}))|(0\\.[0-9]{1,2}))")) {
						Toast.makeText(OrderInfoModifyPop.this, "请输入单价!", Toast.LENGTH_SHORT)
								.show();
						break;
					}
					if (Double.parseDouble(txtOrderPrice.getText().toString()) > 500
							|| Double.parseDouble(txtOrderPrice.getText().toString()) <= 0) {
						Toast.makeText(OrderInfoModifyPop.this, "单价不能超过500元或不能为0!",
								Toast.LENGTH_SHORT).show();
						break;
					}
					thread = new HttpThread(handler);
					thread.doStart(txtSKU.getText().toString());
					break;
				case R.id.btnCancel :
					OrderInfoModifyPop.this.finish();
					break;
				default :
					break;
			}

		}
	};

	private Handler handler = new Handler() {
		public void handleMessage(Message m) {
			switch (m.what) {
				case CommonStatic.STATE_NORMAL :
					OrderDetailBean matnr = (OrderDetailBean) m.getData().getSerializable("matnr");
					if (null != matnr) {
						orderDetail.setBismt(txtSKU.getText().toString().toUpperCase());
						orderDetail.setShop_code(txtShopCode.getText().toString());

						orderDetail.setNum(txtOrderNum.getText().toString());
						orderDetail.setOrderprice(txtOrderPrice.getText().toString());
						java.text.DecimalFormat df = new java.text.DecimalFormat("######0.00");
						double orderMoney = Integer.parseInt(txtOrderNum.getText().toString())
								* Double.parseDouble(txtOrderPrice.getText().toString());

						orderDetail.setTotalprice("" + df.format(orderMoney));
						orderDetail.setRemark(txtOrderComments.getText().toString());
						orderDetail.setMatnr(matnr.getMatnr());
						orderDetail.setMaktx(matnr.getMaktx());
						intent = new Intent();
						bundle = new Bundle();
						bundle.putInt("position", position);
						bundle.putSerializable("orderDetail", orderDetail);
						intent.putExtras(bundle);
						OrderInfoModifyPop.this.setResult(RESULT_OK, intent);
						OrderInfoModifyPop.this.finish();
					}
					break;
				case CommonStatic.STATE_ABNORMAL :
					new AlertDialog.Builder(OrderInfoModifyPop.this).setTitle("提示信息")
							.setMessage("网络异常,请检测手机是否联网!")
							.setNeutralButton("关闭", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dlg, int sumthin) {
								}
							}).show();
					break;
				case CommonStatic.STATE_NORMAL_NULL :
					new AlertDialog.Builder(OrderInfoModifyPop.this).setTitle("提示信息")
							.setMessage("该SKU不存在,请重新输入!")
							.setNeutralButton("关闭", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dlg, int sumthin) {
								}
							}).show();
					break;
			}
		}
	};

	private class HttpThread extends Thread {
		private Handler handle = null;
		private String bismt = null;

		public HttpThread(Handler hander) {
			handle = hander;
		}

		private void doStart(String bismt) {
			this.bismt = bismt;
			progressDialog = new ProgressDialog(OrderInfoModifyPop.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			this.start();
		}

		public void run() {
			Bundle bundle = null;
			try {
				OrderDetailBean matnr = null;
				OrderOpeService orderOpeService = new OrderOpeService();
				matnr = orderOpeService.GetMatnr(bismt);
				if (null != matnr) {
					progressDialog.dismiss();
					Message message = handle.obtainMessage();
					bundle = new Bundle();
					message.what = CommonStatic.STATE_NORMAL;
					bundle.putSerializable("matnr", matnr);
					message.setData(bundle);
					handle.sendMessage(message);
				} else {
					progressDialog.dismiss();
					Message message = handle.obtainMessage();
					bundle = new Bundle();
					message.what = CommonStatic.STATE_NORMAL_NULL;
					message.setData(bundle);
					handle.sendMessage(message);
				}
			} catch (Exception ex) {
				progressDialog.dismiss();
				Message message = handle.obtainMessage();
				bundle = new Bundle();
				message.what = CommonStatic.STATE_ABNORMAL;
				bundle.putString("error", ex.getMessage());
				message.setData(bundle);
				handle.sendMessage(message);

			}
		}
	}

	private void getSession() {
		listUnitInfo = ((ComStaticApp) this.getApplication()).getListUnitInfo();
		position = this.getIntent().getIntExtra("position", -1);
		orderDetail = (OrderDetailBean) this.getIntent().getSerializableExtra("OrderDetail");
	}

	private void findView() {
		txtSKU = (EditText) this.findViewById(R.id.txtSKU);
		txtShopCode = (EditText) this.findViewById(R.id.txtShopCode);
		txtOrderNum = (EditText) this.findViewById(R.id.txtOrderNum);
		txtOrderPrice = (EditText) this.findViewById(R.id.txtOrderPrice);
		txtOrderComments = (EditText) this.findViewById(R.id.txtOrderComments);
		labTxtMatnr = (TextView) this.findViewById(R.id.labTxtMatnr);
		labTxtMaktx = (TextView) this.findViewById(R.id.labTxtMaktx);

		spiUnitInfo = (Spinner) this.findViewById(R.id.spiUnitInfo);

		btnSubmit = (Button) this.findViewById(R.id.btnSubmit);
		btnCancel = (Button) this.findViewById(R.id.btnCancel);
	}

	private void initView() {
		ArrayAdapter<UnitInfoBean> adapter = new ArrayAdapter<UnitInfoBean>(
				OrderInfoModifyPop.this, android.R.layout.simple_spinner_item, listUnitInfo);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spiUnitInfo.setAdapter(adapter);
	}

	public void setView() {
		txtSKU.setText(orderDetail.getBismt());
		txtSKU.setEnabled(false);
		txtShopCode.setText(orderDetail.getShop_code());
		labTxtMatnr.setText(orderDetail.getMatnr());
		labTxtMaktx.setText(orderDetail.getMaktx());
		txtOrderNum.setText(orderDetail.getNum());
		txtOrderPrice.setText(orderDetail.getOrderprice());
		txtOrderComments.setText(orderDetail.getRemark());
		spiUnitInfo.setSelection(getSpinnerSelectedItemPosition(orderDetail.getUnitInfo()), true);
	}

	private int getSpinnerSelectedItemPosition(UnitInfoBean unitInfo) {
		int position = 0;
		for (int i = 0; i < listUnitInfo.size(); i++) {
			if (unitInfo.getUnit().equals(listUnitInfo.get(i).getUnit())) {
				position = i;
			}
		}
		return position;
	}
}
